import { createRouter, createWebHistory } from 'vue-router'
import Chat from '@/views/chat.vue'
import Login from '@/views/login.vue'
import Register from '@/views/register.vue'
import ws from '@/utils/ws.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      name: 'chat',
      component: Chat,
    },
    {
      path: '/register',
      name: 'register',
      component: Register
    }
  ],
})

router.beforeEach((to, from, next) => {
  let token = window.localStorage.getItem('x-token')
  if (token) ws.connect(token)

  // 白名单：允许未登录访问的路径
  const publicPages = ['/login', '/register']

  if (!token && !publicPages.includes(to.path)) {
    next({ path: '/login' }) // 非白名单页面跳转登录
  } else if (token && to.path === '/login') {
    next({ path: '/' }) // 已登录访问 /login 则跳转首页
  } else {
    next() // 正常通行
  }
})


export default router
